package com.example.demo;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class DifferentStyleInputOutputForm extends JFrame {
    private JTextField inputField1;
    private JTextField inputField2;
    private JTextArea outputArea;

    public DifferentStyleInputOutputForm() {
        // 设置窗口标题和大小
        setTitle("不同风格输入输出示例");
        setSize(1250, 1000);
        // 设置窗口关闭操作
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 使用自定义的布局方式
        setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

        // 创建并添加第一个输入框及标签
        JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JLabel label1 = new JLabel("输入1: ");
        label1.setPreferredSize(new Dimension(80, 25));
        inputField1 = new JTextField(100);
        panel1.add(label1);
        panel1.add(inputField1);

        // 创建并添加第二个输入框及标签
        JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JLabel label2 = new JLabel("输入2: ");
        label2.setPreferredSize(new Dimension(80, 25));
        inputField2 = new JTextField(100);
        panel2.add(label2);
        panel2.add(inputField2);

        // 创建并添加提交按钮及事件处理
        JButton submitButton = new JButton("提交");
        submitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                handleSubmit();
            }
        });

        // 创建输出框
        outputArea = new JTextArea(10, 40);
        outputArea.setEditable(false);

        // 将各个组件添加到窗口
        add(panel1);
        add(panel2);
        add(submitButton);
        add(new JScrollPane(outputArea));

        // 设置组件之间的间距
        setComponentPadding();
    }

    private void handleSubmit() {
        String input1 = inputField1.getText();
        String input2 = inputField2.getText();
        // 构建JSON格式数据
        String jsonData = "{" +
                "\"input1\":\"" + input1 + "\"," +
                "\"input2\":\"" + input2 + "\"" +
                "}";
        outputArea.setText(jsonData);
    }

    private void setComponentPadding() {
        Component[] components = getContentPane().getComponents();
        for (Component component : components) {
            if (component instanceof JPanel) {
                ((JPanel) component).setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
            } else if (component instanceof JButton) {
                ((JButton) component).setBorder(BorderFactory.createEmptyBorder(3, 0, 3, 0));
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new DifferentStyleInputOutputForm().setVisible(true);
        });
    }
}